package com.xayy.health.core.antlr4.utils;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.xayy.health.core.antlr4.model.ErrorResult;
import com.xayy.health.core.antlr4.visitor.HealthEvaluateVisitor;
import com.xayy.health.mgt.model.AssessParma;
import com.xayy.health.mgt.model.SatelliteCode;
import com.xayy.health.mgt.service.AssessParmaService;
import com.xayy.health.mgt.service.SatelliteCodeService;

import cn.kawins.base.utils.BeanUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Nie
 * @version V1.0
 * @date 2023/8/16 15:08
 */
@Component
@Slf4j
public class XnUtil {
    private static XnUtil xnUtil;

    @Autowired
    private AssessParmaService assessParmaService;
    @Autowired
    private SatelliteCodeService satelliteCodeService;

    @PostConstruct
    public void init() {
        xnUtil = this;
        xnUtil.assessParmaService = this.assessParmaService;
        xnUtil.satelliteCodeService = this.satelliteCodeService;

    }

    public static Double getXnScore(String satCode, String paramCode, HealthEvaluateVisitor visitor) {
        Double xnValue = Golabl.getXnValue(satCode, paramCode);
        if (xnValue != null) {
            return xnValue;
        }
        SatelliteCode satelliteCode =
            xnUtil.satelliteCodeService.selectOne(SatelliteCode.builder().satelliteCode(satCode).build());
        if (BeanUtil.isEmpty(satelliteCode)) {
            Golabl.setXnValue(satCode, paramCode, 0D);
            return 0D;
        }
        AssessParma assessParma =
            xnUtil.assessParmaService.selectOne(AssessParma.builder().satId(Long.valueOf(satelliteCode.getSatelliteId())).assessCode(paramCode).build());
        if (BeanUtil.isEmpty(assessParma)) {
            Golabl.setXnValue(satCode, paramCode, 0D);
            return 0D;
        }
        ErrorResult execute = FunUtil.execute(assessParma.getVisitor(), visitor);
        if (execute.isSuccess()) {
            Double a = execute.getResult();
            a = a < 0 ? 0 : a;
            a = a > 100 ? 100 : a;
            Golabl.setXnValue(satCode, paramCode, a);
            return a;
        }
        Golabl.setXnValue(satCode, paramCode, 0D);
        return 0D;
    }

}
